#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import pymysql
from config import Config

def check_table_structure():
    """检查MySQL表结构"""
    try:
        conn = pymysql.connect(
            host=Config.DB_HOST,
            port=Config.DB_PORT,
            user=Config.DB_USER,
            password=Config.DB_PASSWORD,
            database=Config.DB_NAME
        )
        
        cursor = conn.cursor()
        
        # 检查sleep_monitoring_records表结构
        print("📊 MySQL中sleep_monitoring_records表结构:")
        cursor.execute('DESCRIBE sleep_monitoring_records')
        mysql_columns = cursor.fetchall()
        
        for row in mysql_columns:
            print(f"  {row[0]} - {row[1]} - {row[2]} - {row[3]}")
        
        print("\n📋 模型中定义的字段:")
        from models.sleep_monitoring import SleepMonitoringRecord
        
        # 获取模型字段
        model_fields = []
        for field_name, field_obj in SleepMonitoringRecord._meta.fields.items():
            field_type = type(field_obj).__name__
            model_fields.append((field_name, field_type))
            print(f"  {field_name} - {field_type}")
        
        print("\n🔍 字段对比:")
        mysql_field_names = [row[0] for row in mysql_columns]
        model_field_names = [field[0] for field in model_fields]
        
        # 检查缺失的字段
        missing_in_mysql = set(model_field_names) - set(mysql_field_names)
        missing_in_model = set(mysql_field_names) - set(model_field_names)
        
        if missing_in_mysql:
            print(f"❌ MySQL表中缺失的字段: {missing_in_mysql}")
        
        if missing_in_model:
            print(f"⚠️  模型中未定义的字段: {missing_in_model}")
        
        if not missing_in_mysql and not missing_in_model:
            print("✅ 字段完全匹配")
        
        conn.close()
        
    except Exception as e:
        print(f"❌ 检查表结构失败: {e}")

def recreate_table():
    """重新创建表"""
    try:
        print("\n🔄 重新创建sleep_monitoring_records表...")
        
        # 重置数据库连接
        from config import reset_database
        reset_database()
        
        from models.sleep_monitoring import SleepMonitoringRecord
        from config import get_database
        
        db = get_database()
        db.connect()
        
        # 删除现有表
        if SleepMonitoringRecord.table_exists():
            SleepMonitoringRecord.drop_table()
            print("✅ 旧表已删除")
        
        # 创建新表
        SleepMonitoringRecord.create_table()
        print("✅ 新表已创建")
        
        db.close()
        
        # 重新检查表结构
        check_table_structure()
        
    except Exception as e:
        print(f"❌ 重新创建表失败: {e}")

def main():
    """主函数"""
    print("🔍 检查MySQL表结构...")
    check_table_structure()
    
    print("\n❓ 是否需要重新创建表? (输入 'y' 确认)")
    # 自动重新创建表
    recreate_table()

if __name__ == '__main__':
    main()